from fastapi import APIRouter, UploadFile, File
from fastapi.responses import StreamingResponse
from app.models.response import ApiResponse
from app.services import video_service
from app.utils.file_utils import validate_file_type
import io

router = APIRouter()

@router.post(
    "/convert",
    summary="视频格式转换",
    description="将视频文件转换为其他格式"
)
async def convert_video(
    file: UploadFile = File(...),
    format: str = "mp4"
):
    try:
        if not validate_file_type(file.filename, ['.mp4', '.avi', '.mkv', '.mov', '.wmv']):
            return ApiResponse(code=400, message="不支持的文件格式")

        content = await file.read()
        converted = await video_service.convert_format(content, format)
        
        return StreamingResponse(
            io.BytesIO(converted),
            media_type=f"video/{format}",
            headers={
                "Content-Disposition": f'attachment; filename="converted.{format}"'
            }
        )
    except Exception as e:
        return ApiResponse(code=400, message=str(e))

@router.post(
    "/compress",
    summary="视频压缩",
    description="压缩视频文件，可调整分辨率、质量和码率"
)
async def compress_video(
    file: UploadFile = File(...),
    resolution: str = "original",
    quality: int = 80,
    bitrate: int = 2000
):
    try:
        if not validate_file_type(file.filename, ['.mp4', '.avi', '.mkv', '.mov', '.wmv']):
            return ApiResponse(code=400, message="不支持的文件格式")

        content = await file.read()
        compressed = await video_service.compress_video(content, resolution, quality, bitrate)
        
        return StreamingResponse(
            io.BytesIO(compressed),
            media_type="video/mp4",
            headers={
                "Content-Disposition": f'attachment; filename="compressed.mp4"'
            }
        )
    except Exception as e:
        return ApiResponse(code=400, message=str(e)) 